import Vue from 'vue'
import Vuex from 'vuex'
import Cart from './Cart'
import Product from './Product'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    datalist: []
  },
  mutations: {
    ADD(state, obj) {
      if(obj instanceof Array){
        state.datalist.push(...obj)
      }else{
        state.datalist.push(obj)
      }
    },
    UPDATE_LIST(state, list) {
      state.datalist = list;
    },
    DEL(state, id) {
      state.datalist.forEach((item, index) => {
        if (item.id === id) {
          state.datalist.splice(index, 1)
        }
      })
    },
    UPDATE(state, obj) {
      state.datalist.forEach((item, index) => {
        if (item.id === obj.id) {
          state.datalist[index]["name"] = obj.name;
          state.datalist[index]["isedit"] = obj.isedit;
        }
      })
    },
    UPDATE_STATUS(state, obj) {
      state.datalist.forEach((item, index) => {
        if (item.id === obj.id) {
          state.datalist[index]["isedit"] = obj.isedit;
        }
      })
    }
  },
  actions: {
    getlist({commit}){
      fetch('http://localhost:3000/datalist').then((res) => res.json()).then((result) => {
        commit('ADD',result)
      })
    }
  },
  getters:{
    pages(state) {
      //查询
      return Math.ceil(state.datalist.length/3);
    }
  },
  modules: {
    Cart,
    Product
  }
})
